/**
 * Copyright 2009 University of Washington This code is released under the GPL version 3 - with a copy of the license
 * included
 * 
 * @author Maya Hao Li
 * 
 */
package seedpod.webapp.view.seedpodwidgets;

import java.util.Enumeration;
import java.util.Hashtable;

import seedpod.exceptions.InvalidWidgetException;
import seedpod.model.AVPair;
import seedpod.model.ProtegeValueType;
import seedpod.model.SeedpodModel.RdbCls.FormWidget;
import seedpod.model.SeedpodModel.RdbCls.ViewWidget;
import seedpod.model.rdb.MetaRdbSlot;

public class Radio extends LimsWidget {

	public Radio() {
	// TODO Auto-generated constructor stub
	}

	public Radio(AVPair avpair) {
		super( avpair );
	}

	@Override
	public FormWidget getFormWidgetType() {
		return FormWidget.RADIO;
	}

	private Hashtable<String, String> getSymbols() {
		Hashtable<String, String> symbolValueHT = new Hashtable<String, String>();

		if ( getAttribute().getProtegeValueType().equals( ProtegeValueType.Boolean ) ) {
			symbolValueHT.put( "yes", "true" );
			symbolValueHT.put( "no", "false" );
		} else {
			String[] values = getAttribute().getAllowedValues().split( MetaRdbSlot.VALUE_DELIMITER );
			for ( String v : values )
				symbolValueHT.put( v, v );
		}
		return symbolValueHT;
	}

	@Override
	public ViewWidget getViewWidgetType() {
		return ViewWidget.RADIO;
	}

	@Override
	public String render() {
		Hashtable<String, String> symbolValuesHT = getSymbols();
		Enumeration<String> symbols = symbolValuesHT.keys();
		String view = "";
		String presetData = getData() != null ? getData().toString() : "";

		while (symbols.hasMoreElements()) {
			String symbol = symbols.nextElement();
			String value = symbolValuesHT.get( symbol );
			view += " <input " + ATT( "id", _widgetID ) + ATT( "name", _widgetID ) + ATT( "type", "radio" ) + ATT(
					"value", value );
			view += value.equalsIgnoreCase( presetData ) ? "checked " : "";
			view += " > ";
			view += symbol;
			view += "<br>";
		}
		return view;
	}

	@Override
	public void validateWidget() throws InvalidWidgetException {
		if ( !getAttribute().getProtegeValueType().equals( ProtegeValueType.Symbol ) || !getAttribute().getProtegeValueType().equals(
				ProtegeValueType.Boolean ) )
			throw new InvalidWidgetException( "(E) Invalid widget for Radio widget. Must be boolean or symbol." );
	}

}